<template>
    <div>
        <!-- 面包屑 -->
        <el-card>
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>{{ isEdit ? '修改商品' : '增加商品' }}</el-breadcrumb-item>
            </el-breadcrumb>
        </el-card>
        <!-- 内容区域 -->
        <el-card>
            <!-- 提示信息区域 -->
            <el-alert :title="isEdit ? '修改商品信息' : '增加商品信息'" type="warning" center show-icon :closable="false">
            </el-alert>

            <!-- 表单 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" class="demo-ruleForm" label-width="100px">
                <!-- 第一行 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="商品名称" prop="name">
                            <el-input v-model="addForm.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商品类别" prop="goodsId">
                            <el-cascader style="width: 100%;" placeholder="分类选择" clearable expand-trigger="hover"
                                :options="parentCateList" v-model="selectedKeys" :props="cascaderProps"
                                @change="parentCateChange">
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商品价格" prop="pprice">
                            <el-input v-model="addForm.pprice" type="number"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="商品库存" prop="kucun">
                            <el-input v-model="addForm.kucun" type="number"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="商品描述" prop="goodsDec">
                            <el-input v-model="addForm.goodsDec" type="textarea" autosize :row="1"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 上传图片 -->
                <el-form-item label="封面图片" prop="imgUrl">
                    <el-input placeholder="网络图片地址" v-model="addForm.imgUrl" :disabled="true">
                        <template slot="prepend">Http://</template>
                    </el-input>
                    <el-upload class="upload-demo" style="width: 300px;" :limit="1"
                        action="http://localhost:2002/api/pic/profile" ref="upload" name="avatar"
                        :on-preview="handlePreview" :on-success="handleSuccess" :on-remove="handleRemove"
                        :before-upload="beforeUpload" list-type="picture" :file-list="fileList">
                        <el-button size="small" type="primary">点击上传图片</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传一张，若需要更新图片，请先移除！</div>
                    </el-upload>
                </el-form-item>
                <!-- 底部区域 -->
                <el-form-item style="text-align: right;">
                    <el-button type="primary" v-if="isEdit" @click="editGoods">立即修改</el-button>
                    <el-button type="primary" @click="addGoods" v-else>立即创建</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 查看大图 -->
        <el-dialog :visible.sync="selectImgDialog" append-to-body width="30%">
            <img width="100%" :src="addForm.imgUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
import { getClassAll } from '@/api/goodsClass/goodsClass'
import { addGoodsAll, updateGoodsAll } from '@/api/goods/goods'
export default {
    data() {
        return {

            addForm: {
                name: '',
                pprice: 0,
                goodsId: '',
                goodsDec: '',
                kucun: 0,
                imgUrl: ''

            },

            //验证规则
            addFormRules: {
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                pprice: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' },
                ],
                kucun: [
                    { required: true, message: '请输入商品库存', trigger: 'blur' },
                ],
                goodsDec: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
                ],
                goodsId: [
                    { required: true, message: '请选择商品类别', trigger: 'blur' },
                ],
                imgUrl: [
                    { required: true, message: '请上传图片', trigger: 'blur' },
                ]

            },
            //选中的父级分类的ID数组
            selectedKeys: [],
            //分类的列表
            parentCateList: [],
            //指定级联选择器的配置对象
            cascaderProps: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
            //查看大图的dialog状态
            selectImgDialog: false,
            //判断是否时修改（true）。默认是增加 (false)
            isEdit: false,
            //图片列表
            fileList: []
        }
    },
    methods: {
        //修改
        editGoods() {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                await updateGoodsAll(this.addForm).then(res => {
                    if (res.data.status == 0) {
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        })
                    }
                })

            })
        },
        //上传图片前触发
        beforeUpload() {
            console.log(this.addForm.imgUrl)
            if (this.addForm.imgUrl) {
                this.$message.error('只能上传一张图片~');
            }
        },
        //移除图片触发
        handleRemove(file) {
            if (file.status == 'success') {
                this.addForm.imgUrl = ''
            }
        },
        //上传图片成功触发
        handleSuccess(file) {
            this.addForm.imgUrl = file.url
        },
        //查看图片大图触发
        handlePreview() {
            this.selectImgDialog = true
        },
        //重置按钮
        reset() {
            this.$refs.addFormRef.resetFields()//清空表单的数据
            this.selectedKeys = [] //清空级联选择器的数据
            this.$refs.upload.clearFiles()//清空已经上传的图片列表
        },
        //添加按钮
        addGoods() {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                await addGoodsAll(this.addForm).then(res => {
                    if (res.data.status == 0) {
                        this.reset()
                        this.$message({
                            message: '添加成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        //获取分类信息
        async getGoodsClass() {
            await getClassAll().then(res => {
                if (res.data.status == 0) {
                    this.parentCateList = res.data.data
                }
            })
        },
        //分类选择器发生改变触发
        parentCateChange() {
            if (this.selectedKeys.length > 0) {
                this.addForm.goodsId = this.selectedKeys[this.selectedKeys.length - 1]
            } else {
                this.addForm.goodsId = ''
            }
        },
    },
    async created() {
        //获取分类信息
        await this.getGoodsClass()
        //判断是否有传递数据
        if (this.$route.query.goodsDtail) {
            //获取传递的数据
            const goodsDtail = JSON.parse(this.$route.query.goodsDtail)
            //赋值数据
            this.addForm = goodsDtail
            //更新页面状态，isEdit=>true:编辑  false:新增
            this.isEdit = true
            //编辑状态时需要手动给图片列表添加已上传的图片
            this.fileList.push({ name: '图片', url: `${goodsDtail.imgUrl}` })
            //获取分类的所有父级id
            this.parentCateList.forEach(item1 => [
                item1.children.forEach(item2 => {
                    item2.children.forEach(item3 => {
                        if (item3.id == goodsDtail.goodsId) {
                            this.selectedKeys = [item1.id, item2.id, item3.id]
                        }
                    })
                })
            ])
        }

    }
}

</script>

<style scoped lang="less">
.el-alert {
    margin: 20px 0 30px 0;
}
</style>
